<template>
    <div class="publish-auction">
        <div class="page-header">
            <h2>发布拍卖品</h2>
            <p class="description">填写以下信息发布您的拍卖品，所有信息提交后会进行审核</p>
        </div>

        <el-card shadow="hover" class="form-card">
            <el-form ref="formRef" :model="auctionForm" :rules="rules" label-width="100px" label-position="left"
                status-icon>
                <!-- 基本信息 -->
                <div class="form-section">
                    <div class="section-title">基本信息</div>

                    <el-form-item label="拍品名称" prop="title">
                        <el-input v-model="auctionForm.title" placeholder="请输入拍品名称" />
                    </el-form-item>

                    <el-form-item label="拍品分类" prop="categoryId">
                        <el-select v-model="auctionForm.categoryId" placeholder="选择分类">
                            <el-option v-for="category in categoryList" :key="category.id" :label="category.name"
                                :value="category.id" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="拍品图片" prop="image">
                        <el-upload class="upload-container" :http-request="handleUpload"
                            :before-upload="beforeUpload" :on-exceed="handleExceed" :limit="1" :file-list="fileList"
                            list-type="picture-card">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            <template #tip>
                                <div class="upload-tip">
                                    请上传清晰的拍品照片，支持jpg、png格式，最大5MB
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="拍品描述" prop="description">
                        <el-input v-model="auctionForm.description" type="textarea" :rows="5"
                            placeholder="请详细描述拍品的特点、来源、品相等信息" />
                    </el-form-item>
                </div>

                <!-- 价格设置 -->
                <div class="form-section">
                    <div class="section-title">价格设置</div>

                    <el-form-item label="起拍价" prop="startPrice">
                        <el-input-number v-model="auctionForm.startPrice" :min="1" :precision="2" :step="10"
                            class="price-input" />
                        <span class="unit">元</span>
                    </el-form-item>
                </div>

                <!-- 拍卖时间 -->
                <div class="form-section">
                    <div class="section-title">拍卖时间</div>

                    <el-form-item label="拍卖时间" prop="auctionTime" class="with-tip">
                        <el-date-picker v-model="auctionForm.auctionTime" type="datetimerange" start-placeholder="开始时间"
                            end-placeholder="结束时间" format="YYYY-MM-DD HH:mm" :default-time="defaultTime"
                            :shortcuts="timeRangeShortcuts" :disabled-date="disabledDate" range-separator="至"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                </div>

                <!-- 提交按钮 -->
                <div class="form-actions">
                    <el-button @click="goBack">返回</el-button>
                    <el-button type="primary" @click="submitForm(formRef)" :loading="submitting">立即发布</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { publishAuction, uploadImage } from '@/api/seller'
import { getUserCategoryList } from '@/api/category'

const router = useRouter()
const formRef = ref(null)
const categoryList = ref([])
const fileList = ref([])
const submitting = ref(false)

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入拍品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择拍品分类', trigger: 'change' }
    ],
    image: [
        { required: true, message: '请上传拍品图片', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入拍品描述', trigger: 'blur' },
        { min: 10, max: 1000, message: '长度在 10 到 1000 个字符', trigger: 'blur' }
    ],
    startPrice: [
        { required: true, message: '请设置起拍价', trigger: 'change' },
        { type: 'number', min: 1, message: '起拍价必须大于0', trigger: 'change' }
    ],
    auctionTime: [
        { required: true, message: '请选择拍卖时间', trigger: 'change' }
    ]
}

// 拍卖表单
const auctionForm = reactive({
    title: '',
    description: '',
    categoryId: '',
    startPrice: 100,
    image: '',
    auctionTime: []
})

// 时间选择快捷方式
const timeRangeShortcuts = [
    {
        text: '1小时',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setHours(end.getHours() + 1)
            return [start, end]
        }
    },
    {
        text: '24小时',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setHours(end.getHours() + 24)
            return [start, end]
        }
    },
    {
        text: '3天',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setDate(end.getDate() + 3)
            return [start, end]
        }
    },
    {
        text: '7天',
        value: () => {
            const start = new Date()
            const end = new Date()
            end.setDate(end.getDate() + 7)
            return [start, end]
        }
    }
]

// 默认时间
const defaultTime = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 1, 1, 23, 59, 59)
]

// 禁用过去的日期
const disabledDate = (time) => {
    return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 上传前验证
const beforeUpload = (file) => {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt5M = file.size / 1024 / 1024 < 5

    if (!isImage) {
        ElMessage.error('只能上传jpg/png格式的图片！')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB！')
        return false
    }
    return true
}

// 处理文件上传
const handleUpload = async ({ file }) => {
    try {
        const res = await uploadImage(file)
        if (res) {
            auctionForm.image = res
            ElMessage.success('图片上传成功')
        } else {
            ElMessage.error('图片上传失败')
        }
    } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('图片上传失败，请重试')
    }
}

// 超出上传数量限制
const handleExceed = () => {
    ElMessage.warning('只能上传1张图片')
}

// 获取分类列表
const fetchCategories = async () => {
    try {
        const res = await getUserCategoryList()
        categoryList.value = res
        console.log('分类列表:', categoryList.value)
    } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
    }
}

// 返回上一页
const goBack = () => {
    router.push('/user/seller/auctions')
}

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return

    formEl.validate(async (valid) => {
        if (!valid) return

        // 确认提交
        ElMessageBox.confirm('确定要发布此拍卖品吗？发布后将进入审核状态。', '确认发布', {
            confirmButtonText: '确定发布',
            cancelButtonText: '再检查一下',
            type: 'info'
        }).then(async () => {
            submitting.value = true

            try {
                // 构建提交数据
                const submitData = {
                    ...auctionForm,
                    startTime: auctionForm.auctionTime[0],
                    endTime: auctionForm.auctionTime[1]
                }
                delete submitData.auctionTime

                const res = await publishAuction(submitData)

                if (res.code === 1) {
                    ElMessage.success('发布成功')
                    router.push('/user/seller/auctions')
                } else {
                    ElMessage.error(res?.msg || '发布失败')
                }
            } catch (error) {
                console.error('发布拍卖品失败:', error)
                ElMessage.error('发布失败，请稍后再试')
            } finally {
                submitting.value = false
            }
        }).catch(() => {
            // 用户取消，不做处理
        })
    })
}

onMounted(() => {
    fetchCategories()
})
</script>

<style scoped>
.publish-auction {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
}

.page-header h2 {
    margin-bottom: 10px;
}

.description {
    color: #606266;
    font-size: 14px;
}

.form-card {
    margin-bottom: 30px;
}

.form-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
    border-bottom: none;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    color: #303133;
}

.price-input {
    width: 200px;
}

.unit {
    margin-left: 10px;
    color: #606266;
}

.with-tip .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.5;
}

.upload-container {
    display: flex;
    flex-direction: column;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 40px;
}
</style>